package ro.isdc.training.jpa.course.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ro.isdc.training.jpa.course.dao.CourseDAO;
import ro.isdc.training.jpa.course.domain.Course;
import ro.isdc.training.jpa.course.domain.CourseId;

/**
 * Course Data Access Object Implementation
 * 
 * @author Andrei Chirila
 */
public class CourseDAOImpl implements CourseDAO {

	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * {@inheritDoc}
	 */
	public Course findCourseByCourseId(CourseId courseId) {
		List<Object> paramValuesList = new ArrayList<Object>();
		List<String> paramNamesList = new ArrayList<String>();

		String sql = "select c from Course c";
		if (courseId != null) {
			if (courseId.getEntityId() > 0) {
				sql += " where c.entityId = :entityId";
				paramNamesList.add("entityId");
				paramValuesList.add(courseId.getEntityId());
			} else {
				sql += " where c.courseName = :courseName";
				paramNamesList.add("courseName");
				paramValuesList.add(courseId.getCourseName());
			}
		}

		return (Course) entityManager.createQuery(sql).setParameter(
				paramNamesList.get(0), paramValuesList.get(0)).getSingleResult();

	}

	/**
	 * {@inheritDoc}
	 */
	public Serializable saveCourse(Course course) {
		entityManager.persist(course);
		return course.getEntityId();
	}

}
